package org.ala.tcp_feign_client.spring.feign.results;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.ala.tcp_feign_client.spring.feign.results.impl.BizRespResultAsyncCallback;
import org.ala.tcp_feign_client.spring.feign.results.impl.BizRespResultSAsyncCallback;


/**
 * 默认的ResultsMapper
 *
 * @author 骆毅(ala)
 * @date 2024年4月22日
 */
public class DefaultTcpFeignClientResultsMapper implements ITcpFeignClientResultsMapper {
	
	
	/**
	 * msgId和Feturn映射
	 */
	protected Map<Long, IBizRespResultCallback> mapper;
	/**
	 * 超时时间
	 */
	protected long timeout;
	/**
	 * 是否专线
	 * <p>	专线模式下，单独提供超时检测对了
	 */
	protected boolean dedicated;
	/**
	 * 检测超时队列
	 */
	protected TcpFeignClientResultsTimeoutQueue timeoutQueue;
	
	
	public DefaultTcpFeignClientResultsMapper(long timeout, boolean dedicated) {
		this.mapper = new ConcurrentHashMap<>();
		this.timeout = timeout;
		
		if (dedicated) {
			timeoutQueue = new TcpFeignClientResultsTimeoutQueue(timeout);
		} else {
			timeoutQueue = TcpFeignClientResultsTimeoutQueue.common(timeout);
		}
	}
	

	@Override
	public void bind(long msgId, IBizRespResultCallback callback) {
		mapper.put(msgId, callback);
		
		//	如果是async或sasync，追加超时检测队列（sync自己就能感知到超时）
		if (callback instanceof BizRespResultAsyncCallback
				|| callback instanceof BizRespResultSAsyncCallback) {
			timeoutQueue.appendTimeoutQueue(callback);
		}
	}
	/**
	 * 绑定超时检测队列
	 */
	protected void bindTimeoutQueue(IBizRespResultCallback callback) {
		
	}
	

	@Override
	public void unbind(long msgId) {
		mapper.remove(msgId);
	}


	@Override
	public IBizRespResultCallback getAndRemove(long msgId) {
//		BizRespResultCallback callback = mapper.get(msgId);
		return mapper.remove(msgId);
//		return callback;
	}
	
	

}
